package dao;

import interfaceDAO.IDAOStation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import domain.HibernateUtil;
import domain.JCDecauxObject;
import domain.JCDecauxQuery;
import domain.Station;

public class DAOStation implements IDAOStation {
	private Map<Integer, JCDecauxObject> mappingIdToRTObject;

	/**
	 * Add RT values retrieve from JC Decaux web service to given station.
	 * 
	 * @param station
	 *            The station to enhance.
	 * @return
	 * @throws IOException
	 */
	private Station enhanceStationWithRTValuesStation(Station station) {
		try {
			if (mappingIdToRTObject == null) {
				mappingIdToRTObject = new JCDecauxQuery().sendRequest();
			}
			JCDecauxObject jcDecauxObj = mappingIdToRTObject.get(station
					.getNumber());

			if (jcDecauxObj != null) {
				station.updateDynamiqueData(jcDecauxObj);
			} else {
				System.err
						.println("Web service didn't retrieve object with number '"
								+ station.getNumber() + "'");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return station;
	}

	public List<Station> getStationByName(String name) {

		ArrayList<Station> stations = new ArrayList<Station>();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Criteria selectCriteria = session.createCriteria(Station.class);

		selectCriteria.add(Restrictions.eq("name", name));
		Collection<?> res = selectCriteria.list();

		if (res != null) {
			for (Object obj : res) {
				Station station = enhanceStationWithRTValuesStation((Station) obj);
				stations.add(station);
			}

		}

		return stations;
	}
}
